package com.yhsimon.distributed_lock.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author： YHSimon
 * @date： 2022-09-07 19:36
 */
public class ZkTest {
    public static void main(String[] args) throws KeeperException, InterruptedException {
        // 获取zookeeper链接
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper("192.168.101.137:2181", 30000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (Event.KeeperState.SyncConnected.equals(event.getState())
                            && Event.EventType.None.equals(event.getType())) {
                        System.out.println("获取链接成功。。。。。。" + event);
                        countDownLatch.countDown();
                    }else if(Event.KeeperState.Closed.equals(event.getState())){
                        System.out.println("关闭链接");
                    }
                }
            });
            countDownLatch.await();

            zooKeeper.create("/test", "haha..".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

            Stat stat = zooKeeper.exists("/test", true);
            if (stat != null) {
                System.out.println("当前节点存在 " + stat.getVersion());
            } else {
                System.out.println("当前节点不存在");
            }

            // 获取一个节点的数据
            byte[] data = zooKeeper.getData("/test", true, stat);
            System.out.println(new String(data));


            // 查询一个节点的所有子节点
            List<String> children = zooKeeper.getChildren("/test", new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    System.out.println("节点的子节点发生变化...");
                }
            });
            System.out.println(children);

            System.in.read();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zooKeeper != null) {
                zooKeeper.close();
            }

        }


    }


}
